package com.sdu.shanyiapi.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sdu.shanyiapi.db.dao.UserDao;
import com.sdu.shanyiapi.db.dao.UserInfoDao;
import com.sdu.shanyiapi.db.pojo.UserEntity;
import com.sdu.shanyiapi.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lihaopeng
 * @version 1.0
 * @project shanyi-api
 * @description 用户
 * @since 2024/4/13 12:27
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.app-secret}")
    private String appSecret;

    @Resource
    private UserDao userDao;

    @Resource
    private UserInfoDao userInfoDao;

    @Override
    public HashMap loginOrRegister(String code, String nickName, String avatar, String sex) {
        // 用临时授权兑换open_id
        String openId = getOpenId(code);

        HashMap map = new HashMap();
        // 是否为已注册用户
        Integer id = userDao.searchAlreadyRegisteredUserByOpenId(openId);
        if (id == null) {
            UserEntity entity = new UserEntity();
            entity.setOpenId(openId);
            entity.setNickName(nickName);
            entity.setAvatar(avatar);
            entity.setSex(sex);
            entity.setStatus((byte) 1);
            Date date = new Date();
            entity.setCreateTime(date);
            // 新用户注册
            userDao.insertUser(entity);
            // 查询新用户的主键值
            id = userDao.searchAlreadyRegisteredUserByOpenId(entity.getOpenId());
            map.put("msg", "注册成功");
        } else {
            map.put("msg", "登录成功");
        }
        // 查询用户信息中的电话号码
        String phone = userInfoDao.searchUserPhoneById(id);
        map.put("id", id);
        map.put("phone", phone);
        return map;
    }


    /**
     * 获取用户微信的open_id
     *
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new RuntimeException("临时登录凭证错误");
        }
        return openId;
    }

    /**
     * 查询用户的简单信息，包括昵称、头像、性别、电话号码
     *
     * @param userId
     * @return
     */
    @Override
    public HashMap searchUserSimpleInfoById(int userId) {
        HashMap map = userDao.searchUserSimpleInfoById(userId);
        String phone = userInfoDao.searchUserPhoneById(userId);
        if (map != null) {
            map.put("phone", phone);
        }
        return map;
    }



}
